<template>
  <div class="app-container">
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="{ row }">
          <el-button
            type="primary"
            size="mini"
            @click="handleUpdate(row)"
          >
            编辑
          </el-button>
          <!-- <el-button
            type="danger"
            size="mini"
            plain
            @click="handleDelete(row.id, $index)"
          >
            删除
          </el-button> -->
        </template>
      </el-table-column>
      <!-- <el-table-column prop="id" label="ID" align="center" width="60" /> -->
      <el-table-column prop="username" label="账号" align="center" />
      <el-table-column prop="nickName" label="用户名" align="center" />
      <el-table-column
        prop="deptId"
        label="角色"
        align="center"
        :formatter="fmtRole"
      />
      <el-table-column prop="sname" label="所属门店" align="center" width="600px" />
      <el-table-column label="创建时间" align="center">
        <template slot-scope="{ row }">
          <span>{{ row.createTime | parseTime }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" class-name="small-padding fixed-width">
        <template slot-scope="{ row }">
          <el-button type="success" size="mini" @click="handlePwd(row.username)">
            修改密码
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="fetchData"
    /> -->

    <el-dialog :title="title" :visible.sync="dialogFormVisible">
      <el-form
        ref="dataForm"
        :model="adminObj"
        label-width="110px"
        style="margin-right: 30px"
        :rules="rules"
      >
        <el-form-item label="账号" prop="username">
          <el-input v-model="adminObj.username" :disabled="title == '编辑'" />
        </el-form-item>
        <el-form-item v-show="title == '新增'" label="密码" prop="note">
          <el-input v-model="adminObj.note" />
        </el-form-item>
        <el-form-item label="用户名">
          <el-input v-model="adminObj.nickName" />
        </el-form-item>
        <el-form-item label="角色">
          <el-radio-group v-model="adminObj.deptId">
            <el-radio v-for="item in sysRoles" :label="item.id">{{ item.name }}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="adminObj.deptId > 200 || adminObj.deptId === 15" label="所属店铺" required>
          <el-select
            v-model="adminObj.openId"
            style="width: 100%"
            placeholder="请选择"
          >
            <el-option
              v-for="item in listSalon"
              :key="item.id"
              :label="item.sname"
              :value="item.id"
              @click.native="clickSalons(item.sname)"
            />
          </el-select>
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false"> 取消 </el-button>
        <el-button type="primary" @click="updateData()"> 确定 </el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getSalonList } from '@/api/txs'
import {
  getAdminsByRole,
  register,
  editAdmin,
  changePwd
} from '@/api/admin'
import Pagination from '@/components/Pagination'
import dayjs from 'dayjs'
import { systemRoles, getRoleName } from '@/utils/enum/roles'

export default {
  components: { Pagination },
  filters: {
    parseTime (time) {
      return dayjs(time).format('YYYY-MM-DD')
    }
  },
  data () {
    return {
      total: 0,
      listQuery: {
        page: 1,
        limit: 13
      },
      sysRoles: systemRoles.filter(x => x.id > 0),
      dialogFormVisible: false,
      adminObj: {
        id: undefined,
        username: '',
        note: '',
        nickName: '',
        deptId: 21,
        openId: '0',
        sname: ''
      },
      title: '',
      list: null,
      listSalon: null,
      listLoading: true,
      rules: {
        // sid: [{ required: true, message: '请选择归属店铺', trigger: 'change' }],
        username: [{ required: true, message: '必填项', trigger: 'blur' }],
        note: [{ required: true, message: '必填项', trigger: 'blur' }]
        // role: [{ required: true, message: '请选择用户角色', trigger: 'change' }]
      }
    }
  },
  created () {
    this.fetchData()
  },
  methods: {
    clickSalons (val) {
      this.adminObj.sname = val
    },
    fmtRole (row) {
      const tmp = getRoleName(row.deptId);
      return tmp === undefined ? '' : tmp;
    },
    fetchData () {
      this.listLoading = true
      getAdminsByRole(202).then(res => {
        this.list = res.data.data
        // this.total = res.data.data.total
        // const index = this.list.findIndex(o => o.id === 5)
        // if (index !== -1) {
        //   this.list.splice(index, 1)
        // }
        this.listLoading = false
      })
      getSalonList().then(res => {
        this.listSalon = res.data.data.map(s => {
          return {
            id: s.id + '',
            sname: s.sname
          }
        })
      })
    },
    // handleCreate () {
    //   this.title = '新增'
    //   // this.adminObj = this.$options.data().adminObj
    //   this.adminObj.username = ''
    //   this.dialogFormVisible = true
    //   this.$nextTick(() => {
    //     this.$refs['dataForm'].clearValidate()
    //   })
    // },
    handleUpdate (row) {
      this.title = '编辑'
      this.dialogFormVisible = true
      this.adminObj = Object.assign({}, row)
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    updateData () {
      this.$refs['dataForm'].validate(valid => {
        if (valid) {
          const tempData = Object.assign({}, this.adminObj)
          if (this.adminObj.deptId < 200 && this.adminObj.deptId !== 15) {
            tempData.openId = '0'
            tempData.sname = '端丽中台'
          }
          if (this.title === '新增') {
            register(tempData).then(res => {
              // console.log(res.data)
              if (res.data.status === 20000) {
                const d = res.data.data
                this.list.unshift(d)
                this.dialogFormVisible = false
                this.$notify({
                  title: res.data.message,
                  message: res.data.status,
                  type: 'success',
                  duration: 2000
                })
              } else {
                this.$notify({
                  title: res.data.error,
                  message: res.data.status,
                  type: 'error',
                  duration: 2000
                })
              }
            })
          } else if (this.title === '编辑') {
            editAdmin(tempData).then(() => {
              const index = this.list.findIndex(v => v.id === this.adminObj.id)
              this.list.splice(index, 1, tempData)
              this.dialogFormVisible = false
              this.$notify({
                title: 'Success',
                message: '更新成功',
                type: 'success',
                duration: 2000
              })
            })
          }
        }
      })
    },
    // handleDelete (id, index) {
    //   this.$confirm('确定要删除吗?', '提示', {
    //     confirmButtonText: '确定',
    //     cancelButtonText: '取消',
    //     type: 'warning'
    //   })
    //     .then(() => {
    //       delAdmin(id).then(() => {
    //         this.$notify({
    //           title: 'Success',
    //           message: '删除成功',
    //           type: 'success',
    //           duration: 2000
    //         })
    //       })
    //       this.list.splice(index, 1)
    //     })
    //     .catch(() => {})
    // },
    handlePwd (username) {
      this.$prompt('请输入新密码', '', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S+/,
        inputErrorMessage: '请输入密码'
      }).then(({ value }) => {
        changePwd({ password: value, username })
          .then(() => {
            this.$message({
              type: 'success',
              message: '密码修改成功'
            })
          })
          .catch(() => {
            this.$message({
              type: 'error',
              message: '密码修改失败，请稍后再试'
            })
          })
      })
      // .catch(() => {
      //   this.$message({
      //     type: 'info',
      //     message: '取消修改'
      //   })
      // })
    }
  }
}
</script>
